package com.hmdp.utils;

import com.hmdp.entity.Key;
import com.hmdp.service.IkeyService;
import com.hmdp.service.impl.KeyServiceImpl;
import org.fisco.bcos.sdk.BcosSDK;
import org.fisco.bcos.sdk.client.Client;
import org.fisco.bcos.sdk.crypto.keypair.CryptoKeyPair;
import org.fisco.bcos.sdk.transaction.manager.AssembleTransactionProcessor;
import org.fisco.bcos.sdk.transaction.manager.TransactionProcessorFactory;
import org.fisco.bcos.sdk.transaction.model.dto.TransactionResponse;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.security.KeyPairGenerator;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;


@Service
public class UpperChain {

    @Resource
    private IkeyService keyService;

    //获取配置文件路径
    public final String configFile = "src/main/resources/config-example.toml";

    public BcosSDK bcosSDK ;
    public Client client ;
    public CryptoKeyPair cryptoKeyPair ;

    public UpperChain() {
        //  初始化FISCO BCOS SDK
        bcosSDK = BcosSDK.build(configFile);
        client = bcosSDK.getClient(1);
        cryptoKeyPair = client.getCryptoSuite().createKeyPair();
        client.getCryptoSuite().setCryptoKeyPair(cryptoKeyPair);
    }

    //患者数据进行上链
    public void addPatientOrder(String id, String encryptedName, String encryptedPhone, String encryptedPassword, String encryptedType) throws Exception {

        // 加载智能合约
        AssembleTransactionProcessor transactionProcessor = TransactionProcessorFactory.createAssembleTransactionProcessor(client, cryptoKeyPair, "src/main/resources/abi/","");
        // 创建调用交易函数的参数，此处为传入一个参数
        List<Object> params = new ArrayList<>();
        //params.add(encryptedId);
        params.add(id);
        params.add(encryptedName);
        params.add(encryptedPhone);
        params.add(encryptedPassword);
        params.add(encryptedType);

        // 调用智能合约的addOrder方法
        TransactionResponse transactionResponse = transactionProcessor.sendTransactionAndGetResponseByContractLoader("PatientInsertContract", "0xb0c03b99621ccb5c565ee6d2c705eec6685df9c2", "addPatient", params);
        // System.out.println("区块链返回的状态值是："+transactionResponse.getTransactionReceipt().getStatus());
        if(transactionResponse!=null){
            String flag =transactionResponse.getTransactionReceipt().getStatus();
            if("0x0".equals(flag)){
                // 获取交易哈希
                String transactionHash = transactionResponse.getTransactionReceipt().getTransactionHash();
                System.out.println("订单上链成功,交易哈希: "+transactionHash);
            }else {
                System.out.println("交易上链失败");
                // 获取错误信息
                String errorMessage = transactionResponse.getTransactionReceipt().getMessage();
                System.out.println("错误信息: " + errorMessage);
            }
        }else{
            System.out.println("交易发送失败");
        }

    }

    //患者查询
    public void getPatientOrder(String id,String privatekey) throws Exception {

        //将获得的id先进行加密处理
        //String encryptedId = rsaEncrypt(id);
        // System.out.println(encryptedId);
        List<Object> params = new ArrayList<>();
        params.add(id);
        // 加载智能合约
        AssembleTransactionProcessor transactionProcessor = TransactionProcessorFactory.createAssembleTransactionProcessor(client, cryptoKeyPair, "src/main/resources/abi/","");
        // 调用智能合约的getOrder方法
        //Tuple6<String, String, String, String, String, String> result = orderContract.getOrder(rsaEncrypt(id));
        TransactionResponse callResponse = transactionProcessor.sendTransactionAndGetResponseByContractLoader("PatientInsertContract", "0xb0c03b99621ccb5c565ee6d2c705eec6685df9c2", "getPatient",params);

        System.out.println(callResponse);
        System.out.println(callResponse.getReturnObject());
        //打印返回值
        List<Object>results = callResponse.getReturnObject();


        System.out.println("链上传回的加密id "+(String)results.get(0));
        System.out.println("链上传回的加密userid "+(String)results.get(1));

        String PatientId =(String)results.get(0);
        String PatientName =(String) results.get(1);
        String PatientPhone = (String) results.get(2);
        String PatientPassword = (String) results.get(3);
        String PatientType = (String) results.get(4);


        //解密处理
        Encryption encryption = new Encryption();
        String decryptedPatientName = encryption.rsaDecrypt(PatientName,privatekey);
        String decryptedPatientPhone = encryption.rsaDecrypt(PatientPhone,privatekey);
        String decryptedPatientPassword = encryption.rsaDecrypt(PatientPassword,privatekey);
        String decryptedPatientType= encryption.rsaDecrypt(PatientType,privatekey);



        System.out.println("患者id:"+ PatientId);
        System.out.println("患者姓名:"+ decryptedPatientName);
        System.out.println("患者手机号"+decryptedPatientPhone);
        System.out.println("患者密码"+decryptedPatientPassword);
        System.out.println("信息重要程度"+decryptedPatientType);
        // System.out.println("创建时间: " + decryptedCreateTime);
    }

}
